package com.zyh.block;

import java.util.concurrent.LinkedBlockingDeque;

/**
 * @Author zyh
 * @Date 2024/8/9 14:54
 * @Description LinkedBlockQueue
 */

public class LinkedBlockQueueDemo {
    public static void main(String[] args) {
        //创建LinkedBlockQueue
        LinkedBlockingDeque<Integer> queue = new LinkedBlockingDeque<>();
        //创建生产者线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "开始生产数据");
                for (int i = 1; i <= 1000; i++) {
                    //模拟生产时间
                    try {
                        Thread.sleep(1000);
                        queue.offer(i);
                        System.out.println(Thread.currentThread().getName() + "生产了" + i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "生产者").start();
        //创建消费者线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("开始消费数据");
                while (true) {
                    //模拟消费时间
                    try {
                        Thread.sleep(2000);
                        Integer take = queue.take();
                        System.out.println(Thread.currentThread().getName() + "消费了" + take);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "消费者").start();
    }
}
